'use strict';

const Controller = require('egg').Controller;
const await = require('await-stream-ready/lib/await');
const md5 = require('md5');

class LiveController extends Controller {
    // 创建直播间
    async save() {
        const { ctx, app } = this
        const user_id = ctx.authUser.id
        // 参数验证
        ctx.validate({
            title: {
                type: 'string',
                required: true,
                desc: '直播间标题'
            },
            cover: {
                type: "string",
                required: false,
                desc: '直播间封面'
            }
        })
        let { title, cover } = ctx.request.body
        // 生成唯一key
        let key = ctx.randomString(20)
          // 生成签名
          let sign = this.sign(key)
        // 直接创建
        let res = await app.model.Live.create({
            title,
            cover,
            user_id,
            key,
            sign
        })
        ctx.apiSuccess({
            data: res,
            sign
        });
    }
    // 再次开启直播间
    async resave() {
        const { ctx, app } = this
        const user_id = ctx.authUser.id

        // 参数验证
        ctx.validate({
            live_id:{
                type: 'int',
                required: true,
                desc: '直播间id'
            },
            
        })
        let { live_id} = ctx.request.body
        // console.log('aaaaaaaaaaaaaaaaaaaaa',live_id)
        let live=await app.model.Live.findOne({
            where:{
                id:live_id,
                user_id
            }
        })
        if(!live){
            ctx.throw(400,'直播间不存在')
        }
        // 生成唯一key
        let key = ctx.randomString(20)
          // 生成签名
          let sign = this.sign(key)
        live.key=key
        live.status=1
        await live.save()
       
        ctx.apiSuccess({
            data: live,
            sign
        });
    }
    // 生成签名
    sign(key) {
        let { ctx, app } = this;
        const secret = app.config.mediaServer.auth.secret
        const expire = parseInt((Date.now() + 7200000) / 1000); //100000000 过期时间11位数 如2个小时: 3600*2*1000
        const hashValue = md5(`/live/${key}-${expire}-${secret}`);//  /live 路径 key唯一标识  expire 时间  secret字符串
        return `${expire}-${hashValue}`
    }

    // 修改直播间状态
    async changeStatus() {
        const { ctx, app } = this
        let user_id = ctx.authUser.id
        ctx.validate({
            id: {
                type: 'int',
                required: true,
                desc: '直播间id'
            },
            type: {
                type: 'string',
                required: true,
                range: {
                    in: ['play', 'pause', 'stop']
                },
                desc: '状态类型'
            }
        })
        let { id, type } = ctx.request.body

        let live = await app.model.Live.findOne({
            where: {
                id,
                user_id
            }
        })
        if (!live) {
            ctx.throw(400, '直播间不存在')
        }
        // if (live.status == 3) {
        //     ctx.throw(400, '该直播间已结束')
        // }
        const status = {
            play: 1, pause: 2, stop: 3
        }
        live.status = status[type]
        await live.save()
        ctx.apiSuccess('ok')
    }
    // 直播间列表
    async list(){
        const {ctx,app}=this
        ctx.validate({
            page:{
               type:"int",
               required:true,
               desc:'页码' 
            }
        })
        let page=ctx.params.page
        let limit=10;
        let offset=(page-1)*limit
        let rows = await app.model.Live.findAndCountAll({
            offset,
            limit
        })
        ctx.apiSuccess(rows)

    }
    // 进入直播间 
    async read(){
        const {ctx,app}=this
        ctx.validate({
            id:{
                type:'int',
                required:true,
                desc:'直播间ID'
            }
        })
        let id=ctx.params.id
        // console.log('id-----------',id)
        let live=await app.model.Live.findOne({
            where:{
                id
            },
            include:[{
                model:app.model.User,
                attributes:['id','username','avatar']
            }]
        })
        // console.log('id-----------')

        if(!live){
            ctx.throw(400,'直播间不存在')
        }
        let sign=null
        sign=this.sign(live.key)
        // console.log('id-----------',sign)
      
        ctx.apiSuccess({live,sign})
    }
    // 查看主播直播间
    async seeLive(){
        const {ctx,app}=this
        const user_id=ctx.authUser.id

        let liveList=await app.model.Live.findAndCountAll({
            where:{
                user_id
            }
        })
        ctx.apiSuccess(liveList)
    }

}

module.exports = LiveController;
